﻿using UnityEngine;

namespace Assets.Scripts.Bvh.Common
{
    public struct AABB
    {
        public Vector3 minCorner;
        public Vector3 maxCorner;
        public Triangle triangle;

        public Vector3 center => (minCorner + maxCorner) * 0.5f;
        public Vector3 size => maxCorner - minCorner;

        //初始化数据
        public readonly static AABB Invalid = new AABB()
        {
            minCorner = Vector3.one * float.MaxValue,
            maxCorner = Vector3.one * float.MinValue,
            triangle = Triangle.Invalid
        };

        //两个AABB合并计算
        public AABB Union(Vector3 min, Vector3 max)
        {
            var minX = Mathf.Min(minCorner.x, min.x);
            var minY = Mathf.Min(minCorner.y, min.y);
            var minZ = Mathf.Min(minCorner.z, min.z);

            var maxX = Mathf.Max(maxCorner.x, max.x);
            var maxY = Mathf.Max(maxCorner.y, max.y);
            var maxZ = Mathf.Max(maxCorner.z, max.z);

            return new AABB()
            {
                minCorner = new Vector3(minX, minY, minZ),
                maxCorner = new Vector3(maxX, maxY, maxZ),
                triangle = Triangle.Invalid
            };
        }

        //计算一个三角面的AABB
        public static AABB CalFromTriangle(Triangle triangle)
        {
            var minCorner = Vector3.one * float.MaxValue;
            var maxCorner = Vector3.one * float.MinValue;
            minCorner.x = Mathf.Min(minCorner.x, triangle.v0.x, triangle.v1.x, triangle.v2.x);
            minCorner.y = Mathf.Min(minCorner.y, triangle.v0.y, triangle.v1.y, triangle.v2.y);
            minCorner.z = Mathf.Min(minCorner.z, triangle.v0.z, triangle.v1.z, triangle.v2.z);
            maxCorner.x = Mathf.Max(maxCorner.x, triangle.v0.x, triangle.v1.x, triangle.v2.x);
            maxCorner.y = Mathf.Max(maxCorner.y, triangle.v0.y, triangle.v1.y, triangle.v2.y);
            maxCorner.z = Mathf.Max(maxCorner.z, triangle.v0.z, triangle.v1.z, triangle.v2.z);
            var aabb = new AABB()
            {
                minCorner = minCorner,
                maxCorner = maxCorner,
                triangle = triangle,
            };
            return aabb;
        }
    }
}
